#! /usr/bin/perl

#use the HMTLSubs package and ValidationSubs package as well as the database
use HTMLSubs;
use ValidationSubs;
use DBQueries;
use CGI;

#also enable strict mode
use strict;

#start by determining if any information was passed to the script so that the proper actions can be taken
#obtain the input 
my $input = obtain_input();

#ensure that input is not blank which would mean that the site is illegally accessed
if(length($input) == 0){
	
	#if so, redirect to login
	print CGI -> redirect("login.pl.cgi");
}

#declare username to hold owner of the group
my $username;

#call method to split the full string into a hash of individual variables
#this subroutine returns a reference to the submitted info hash
my $ref_submitted_info = HTMLSubs->decode_input($input);

#dereference the submitted info
my %submitted_info = %$ref_submitted_info;

#if the only input is username i.e. the size is 1, 
if(scalar(keys %submitted_info) == 1){
	
	#therefore isolate the username and proceed
	$username = $submitted_info{'username'};
	
	#now call the subroutine to display the group submission form
	display_group_submission("");
}
#otherwise we know a new group was submitted so act accordingly
else{
	
	#now call subroutine to process input
	#pass this sub the reference to submitted info
	#this subroutine will take control of the flow of the script and determine what actions to further take
	#print "about to proces submission\n";
	process_group_submission($ref_submitted_info);
}

#subroutine to both determine the validity of the users input and to process all data
sub process_group_submission{
	
	#obtain group information from parameter
	my $ref_group_info = $_[0];
	
	#dereference hash to local variable
	my %group_info = %$ref_group_info;
	
	#obtain username
	$username = $group_info{'username'};
	
	#now validate the group name
	if(ValidationSubs->validate_group($group_info{'groupName'}) == 1){
		
		#in this case the group submission is valid so create the group and then show the success page 
		#this success page also alows the user to manage group members as well as group files
		#now add to DB
		DBQueries::addGroup($username, $group_info{'groupName'});
		
		#now show the success page and pass it the group name
		show_success($group_info{'groupName'});
	}
	#otherwise the group name is empty or already exists
	else{
		#declare error message
		my $main_error_message = "<h4><font color=\"red\">Your group could not be created because your name was empty or taken. <br>Please try again.</font></h4>";
		
		#now call subroutine to display submission once again and pass it the error message
		display_group_submission($main_error_message);
	}
}

#subroutine that is called whenever the user succesfully submits a group
#this subroutine will display a success message to the user and then allow him/her to manage files and users
#this sub is passed one parameter, the group name
sub show_success{
	
	#obtain parameter
	my $group_name = $_[0];
	
	#call method to display html beginnign
	HTMLSubs->generate_html_beginning("Successfully Created $group_name!");
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "Successfully Created New Group", $username);
	
	print <<END_HTML;
	
	<!--now display the message to the user-->
	<h4>You can manage your new group in your profile.</h4>
	<br>
	
END_HTML

	#create hash for button
	my %username_hash;
	$username_hash{'username'} = $username;
	
	#call subroutine to display button that returns the user to the profile
	HTMLSubs -> generate_html_button("profile.pl.cgi", "Go To profile", \%username_hash);

	#now call method to produce closing html tags
	HTMLSubs->generate_html_end();
}

#subroutine to display the page that allows for a new group to be submitted
sub display_group_submission{
	
	#obtain potential messages
	my $error_text = $_[0];
	
	#start by calling the subroutine from the module to generate the beginning html code
	HTMLSubs->generate_html_beginning("Create New Group");
	
	#next call internal subroutine to generate the html code for the submission from
	#this form will be targeted back to the same script so pass the name as a parameter
	generate_submission_html($ENV{'SCRIPT_NAME'}, $error_text);
	
	#lastly call subroutine to print the closing html tags
	HTMLSubs->generate_html_end();
}

#subroutine to create the html group sumbission form
#this sub is passed the name of the target for the form
sub generate_submission_html{
	
	#obtain target
	my $form_target = $_[0];
	my $error_text = $_[1];
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "Create New Group", $username);
	
	print <<END_HTML;
	
	<div class="content">
END_HTML
	#print any potential error messages passed to the subroutine and ensure that not too many <br> tags are printed
	#by determining if the length of the text is 0 or not
	if(length($error_text) != 0){
		print "<p>$error_text</p>";
	}
	#print actual form
	print <<END_HTML;
	<table>
			<form action="$form_target" method=POST>
			<tr>
				<!-- group name-->
				<td><p>Group Name:*</p></td>
				<td><input type="text" name="groupName"></td>
				
				<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
				<input type="hidden" name="username" value="$username">
			</tr>
			<tr>
				<!--submit button-->
				<td><input type="submit" value="Submit"></form>
END_HTML
		#create cancel button
		#create parameter hash
		my %parameter_hash;
		$parameter_hash{'username'} = $username;
		
		#call subroutine to crate a cancel button
		#this button will link back to profile
		HTMLSubs -> generate_html_button("profile.pl.cgi", "Cancel", \%parameter_hash);
		
			#print remaining tags
			print <<END_HTML;
				</td>
			</tr>
	</table
END_HTML
}


#subroutine to obtain and determine what information is passed to the script
#to make this more universal, both GET and POST methods are accepted 
#this reads input for both GET and POST
sub obtain_input{

	#declare scalar to hold passed information
	my $input;

	#now retrieve the input through either get or post
	#change the case of request method
	$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

	#if post use STDIN
	if ($ENV{'REQUEST_METHOD'} eq "POST"){
		read(STDIN, $input, $ENV{'CONTENT_LENGTH'});

		#exchange plus signs to spaces
		$input =~ s/\+/ /;

		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	#otherwise the env hash
	else{
		$input = $ENV{'QUERY_STRING'};
		
		#exchange plus signs to spaces
		$input =~ s/\+/ /;
		
		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	
	#now return the correct input
	return $input;	
}


	